TypeScript 泛型使用2-常见的工具类型

December 02, 2021

TypeScript 封装了很多常见的基于泛型类型工具把常见的列举出来

Partial<T>

这个类型“函数”的作用,在于给定一个输入的 object 类型 T,返回一个新的 object 类型,这个 object 类型的每一个属性都是可选的。 我们可以用基本的关键字来用自己的方式实现这个工具类型:

type MyPartial<T> = {
  [K in keyof T]?: T[K];
};
type PartialUser = MyPartial<User>;
// {name?: string, age?: number}
type TUserKeys = keyof User;
// 'name' | 'age'
type TName = User["name"];
// string
type TAge = User["age"];
// number
type TUserValue = User[TUserKeys];
// string | number

Required<T>

这个类型“函数”的作用 是标记属性都是必须的,举个例子:

interface Props {
  a?: number;
  b?: string;
}

const obj: Props = { a: 5 };

const obj2: Required<Props> = { a: 5 };
// Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.

Required 具体代码实现如下:


type MyRequired<T> = {
  [K in keyof T]-?: T[K];
};

Readonly<T>

转换成只读

interface Todo {
  title: string;
}

const todo: Readonly<Todo> = {
  title: "Delete inactive users",
};

todo.title = "Hello";
// Cannot assign to 'title' because it is a read-only property.

// 具体实现
type MyReadonly<T> = {
  readonly [K in keyof T]: T[K];
};

Mutable<T>

把ReadOnly 转换成可编辑,一般不会用这种写法,因为定义了readonly,又去改变,会很流氓

type MyMutable<T> = {  -readonly [K in keyof T]: T[K];};

interface User1 {
  readonly id: number;
  readonly name: string;
}
const user1: MyMutable<User1> = {
  id: 1,
  name: "test"
}
user1.id = 35

Record<Keys,Type>

Record 表示把 Type做成做key 对应值的类型,组成一个新的类型,这个非常实用,实际开发中,经常会遇到这种类型组装的问题,案例如下:

interface PageInfo {
  title: string;
}

type Page = "home" | "about" | "contact";

const nav: Record<Page, PageInfo> = {
  about: { title: "about" },
  contact: { title: "contact" },
  home: { title: "home" },
};
// 这里 nav 对应的类型就是一个重新组装的
nav.about;
// ^ = const nav: Record

对应实现如下:


type MyRecord<K extends keyof any, T> = {
  [P in K]: T;
};
type TKeyofAny = keyof any;
// string | number | symbol
type TKeys = "a" | "b" | 0;
type TKeysUser = MyRecord<TKeys, User>;
// {a: User, b: User, 0: User}

Pick<Type, Keys>

这个用的特别多,表示从一个类型里取出你需要用的类型,组成一个新类型,案例如下:

interface Todo {
  title: string;
  description: string;
  completed: boolean;
}

type TodoPreview = Pick<Todo, "title" | "completed">;

// 这里 todo类型就是 只有 title 和 completed 2个属性了
const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
};

对应实现如下:


type MyPick<T, K extends keyof T> = {
  [P in K]: T[P];
};
type TNameKey = "id";
type TUserName = MyPick<User, TNameKey>;
// {id: number}

Exclude<Type, ExcludedUnion>、Extract<Type, Union>、NonNullable<Type>

这 3 个比较像,放到一起

Exclude<Type, ExcludedUnion>

取排除 ExcludedUnion 的属性

type T0 = Exclude<"a" | "b" | "c", "a">;
//    ^ = type T0 = "b" | "c"
type T1 = Exclude<"a" | "b" | "c", "a" | "b">;
//    ^ = type T1 = "c"
type T2 = Exclude<string | number | (() => void), Function>;
//    ^ = type T2 = string | number

Extract<Type, Union>

取 2 者相同的部分

type T0 = Extract<"a" | "b" | "c", "a" | "f">;
//    ^ = type T0 = "a"
type T1 = Extract<string | number | (() => void), Function>;
//    ^ = type T1 = () => void

NonNullable<Type>

取非 null,undefined 部分

type T0 = NonNullable<string | number | undefined>;
//    ^ = type T0 = string | number
type T1 = NonNullable<string[] | null | undefined>;
//    ^ = type T1 = string[]

三者对应实现

type MyExclude<T, U> = T extends U ? never : T;
type MyExtract<T, U> = T extends U ? T : never;
type MyNonNullable<T> = T extends null | undefined ? never : T;

Omit``<Type, Keys>

和 Pick 对应的,我们有时候一个 类型属性非常多,我可能是想排除某几个属性,把剩下的组成一个新类型,就需要 Omit 了,案例如下:

interface Todo {
  title: string;
  description: string;
  completed: boolean;
}
// 排除掉  description 属性,留下其他的
type TodoPreview = Omit<Todo, "description">;

const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
};

对应代码实现:

type MyOmit<T, K> = Pick<T, Exclude<keyof T, K>>;
type OmitUser = MyOmit<User, "age">;
// { name: string }

ConstructorParameters<Type>

取出 构造函数的参数类型,构造函数也就是我们常看到的 new (…args: any) => any,要取到 args,案例如下:

 	class User {
    constructor(id: string, name: number) {}
  }
  type Params = ConstructorParameters<typeof User>
  // [id: number, name: string]

这样 Params 就就是 class User 参数类型了,我们在往前走一步,把 User 改成一个抽象类,这个时候就会报错 image.png 因为 抽象类是没有 new (…args: any) => any) 这属性的,这个时候改变下


abstract class User {
    constructor(id: number, name: string) {}
  }
type ConstructorHelper<T> = (new (...args: any) => any) & T;
type ContructorParameters<T> = ConstructorParameters<ConstructorHelper<T>>;
type Params2 = MyConstructorParameters<typeof User>;
// [id: number, name: string]                                     
                                        

又可以愉快的玩耍了,所以 ConstructorParameters 的特点是记住需要有 new (…args: any) => any) 类型

InstanceType<T>

InstanceType<T> 是表示构造函数的类型,也就是 我们常说的 class 类型,案例如下:

class User {
    id: number;
    name: string;
    constructor(id: number, name: string) {}
    say() {

    }
 }
type Ins = InstanceType<typeof User>;
const mm: Ins = new User(1, '王二');

代码实现:


type MyInstanceType<T extends new (...args: any) => any> = T extends new (
  ...args: any
) => infer R
  ? R
  : any;

其他

以下几个类型,平常基本没有到,列举出来,具体看文档

  • ThisParameterType<Type>
  • OmitThisParameter<Type>
  • ThisType<Type>